package com.hxzy.dao.Impl;

import com.hxzy.bean.Message;
import com.hxzy.bean.User;
import com.hxzy.dao.UserDao;
import com.hxzy.util.JdbcUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class UserDaoImpl implements UserDao {
    @Override
    public int save(User user) {
        String sql="INSERT INTO `message_users` (nick_name,account,login_password,state) VALUES(?,?,?,?)";
        Object[] params={user.getNickName(),user.getAccount(),user.getLoginPassword(),user.getState()};
        return JdbcUtils.executeUpdate(sql,params);
    }

    @Override
    public int update(User user) {
        String sql="UPDATE message_users set nick_name=?,account=?,login_password=?,state=?  WHERE id=?";
        Object[] params={user.getNickName(),user.getAccount(),user.getLoginPassword(),user.getState(),user.getId()};
        return JdbcUtils.executeUpdate(sql,params);
    }

    @Override
    public int remove(Integer integer) {
        String sql="DELETE FROM message_users WHERE id=?";
        return JdbcUtils.executeUpdate(sql,integer);
    }

    @Override
    public List<User> queryAll() {
        String sql="SELECT id,nick_name nickName,account,login_password loginPassword,state FROM `message_users`";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql);
        List<User> collect = list.stream().map(t -> {
            Long id = (Long) t.get("id");
            int i = id.intValue();
            String nickName = (String) t.get("nickName");
            String account = (String) t.get("account");
            String loginPassword = (String) t.get("loginPassword");
            int state = (int) t.get("state");
            return new User(i, nickName, account, loginPassword,state);
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public User findById(Integer integer) {
        String sql="SELECT id,nick_name nickName,account,login_password loginPassword,state FROM `message_users` WHERE id=?";
        List<User> users = JdbcUtils.selectSingleTab(User.class, sql, integer);
        return users !=null?users.get(0):null;
    }

    @Override
    public User findByAccount(String account) {
        String sql="SELECT id,nick_name nickName,account,login_password loginPassword,state FROM message_users WHERE account=?";
        List<User> users = JdbcUtils.selectSingleTab(User.class, sql, account);
        return users !=null?users.get(0):null;
    }
}
